import { toLonLat } from 'ol/proj'
import { fromLonLat, toSureFixed } from './utils'
import { getDistance } from 'ol/sphere'
import * as turf from '@turf/turf'

const PROJECTION3857 = 'EPSG:3857'
const LONLATTYPE = 'fromLonLat'
class WLngLat {
	constructor(option1, option2, option3, option4) {
		if (Array.isArray(option1)) {
			this.init(...option1, option2, option3)
		} else {
			this.init(option1, option2, option3, option4)
		}
	}

	init(lng, lat, lonLatType = LONLATTYPE, proj = PROJECTION3857) {
		const coordinate = lonLatType === LONLATTYPE ? this.fromLonLat([lng, lat], proj) : this.toLonLat([lng, lat], proj)
		// this.lonLatType = lonLatType

		this.olat = lonLatType === LONLATTYPE ? coordinate[1] : lat
		this.olng = lonLatType === LONLATTYPE ? coordinate[0] : lng

		this.lat = lonLatType === LONLATTYPE ? lat : coordinate[1]
		this.lng = lonLatType === LONLATTYPE ? lng : coordinate[0]
	}

	// 经纬度坐标转换 EPSG:4326 - 投影的坐标 projection
	fromLonLat(coordinate, proj = PROJECTION) {
		if (coordinate && Array.isArray(coordinate)) {
			return fromLonLat(coordinate, proj).map(n => toSureFixed(n, 6))
		} else {
			throw TypeError('请出传入正确经纬度！')
		}
	}

	// 投影的坐标 projection  - 经纬度坐标转换 EPSG:4326
	toLonLat(coordinate, proj = PROJECTION) {
		if (coordinate && Array.isArray(coordinate)) {
			return toLonLat(coordinate, proj).map(n => toSureFixed(n, 6))
		} else {
			throw TypeError('请出传入正确经纬度！')
		}
	}
	getLngLat() {
		return [this.lng, this.lat]
	}
	getLng() {
		return this.lng
	}
	getLat() {
		return this.lat
	}
	// 当前经纬度坐标值经度移动w，纬度移动s，得到新的坐标。
	// 经度向右移为正值，纬度向上移为正值，单位为米。
	offset(x, y) {
		let feature = turf.point([this.lng, this.lat])
		let translatedPoly = turf.transformTranslate(feature, x, 0, { units: 'meters' })
		if (x < 0) {
			translatedPoly = turf.transformTranslate(feature, x, -90, { units: 'meters' })
		}
		let coordinates = translatedPoly.geometry.coordinates
		feature = turf.point(coordinates)
		if (y < 0) {
			translatedPoly = turf.transformTranslate(feature, y, 180, { units: 'meters' })
		} else {
			translatedPoly = turf.transformTranslate(feature, y, 90, { units: 'meters' })
		}
		const [lng, lat] = translatedPoly.geometry.coordinates

		this.init(lng, lat)

		return this
	}
	// 当前经纬度和传入经纬度或者经纬度数组连线之间的地面距离，单位为米
	distance(lnglat) {
		if (!lnglat) return
		const coordinates = toLonLat(fromLonLat(lnglat, projection))
		const distance = getDistance([this.lng, this.lat], coordinates)
		return distance
	}
	// 坐标在中国以外
	outOfChina(lat, lng) {
		if (lng < 72.004 || lng > 137.8347) return true
		if (lat < 0.8293 || lat > 55.8271) return true
		return false
	}
}

export default WLngLat
